package com.linzm.leetcode.mid.tree.其他;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @Author zimingl
 * @Date 2023/2/26 18:47
 * @Description: 左叶子之和
 * 给定二叉树的根节点 root ，返回所有左叶子之和。
 * <p>
 * 节点数在 [1, 1000] 范围内
 * -1000 <= Node.val <= 1000
 */
public class Demo15SumOfLeftLeaves404 {
    public static void main(String[] args) {
        Demo15SumOfLeftLeaves404 demo15SumOfLeftLeaves404 = new Demo15SumOfLeftLeaves404();
        int sumNum = demo15SumOfLeftLeaves404.sumOfLeftLeaves(TreeNode.getTree());
        System.out.println(sumNum);
    }

    // 递归
    public int sumOfLeftLeaves(TreeNode root) {
        dfs(root);
        return sum;
    }

    int sum = 0;

    private void dfs(TreeNode root) {
        if (root == null) return;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            sum += root.left.val;
        }
        dfs(root.left);
        dfs(root.right);
    }

    // 递归
    public int sumOfLeftLeaves2(TreeNode root) {
        if (root == null) return 0;
        int leftValue = sumOfLeftLeaves2(root.left);    // 左
        int rightValue = sumOfLeftLeaves2(root.right);  // 右

        int midValue = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            midValue = root.left.val;
        }
        int sum = midValue + leftValue + rightValue;  // 中
        return sum;
    }

    public int sumOfLeftLeaves3(TreeNode root) {
        if (root == null) return 0;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        int result = 0;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null && node.left.left == null && node.left.right == null) {
                result += node.left.val;
            }
            if (node.right != null) stack.add(node.right);
            if (node.left != null) stack.add(node.left);
        }
        return result;
    }

    // 层序遍历
    public int sumOfLeftLeaves4(TreeNode root) {
        int sum = 0;
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) { // 左节点不为空
                    queue.offer(node.left);
                    if (node.left.left == null && node.left.right == null) { // 左叶子节点
                        sum += node.left.val;
                    }
                }
                if (node.right != null) queue.offer(node.right);
            }
        }
        return sum;
    }
}
